<template>
  <el-upload
    action=""
    list-type="picture-card"
    accept="image/*"
    :limit="1"
    :auto-upload="false"
    :on-preview="handlePictureCardPreview"
    :before-upload="beforeUpdata"
    :on-change="handleChange"
    :on-remove="Remove"
    class="upload_ewm">
      <el-icon class="upload_icon"> <plus /></el-icon>
  </el-upload>
  <el-dialog v-model="dialogVisible">
    <img w-full :src="dialogImageUrl" alt="Preview Image" />
  </el-dialog>
</template>
<script setup lang="ts">
  import { ref, reactive, onUnmounted, computed } from 'vue';
  import { ElForm, ElMessage } from 'element-plus'
  import { Plus, ZoomIn, Delete } from '@element-plus/icons-vue'
  import type { UploadFile } from 'element-plus/es/components/upload/src/upload'
  import {  uploadFile2 } from '@/api/common'
  const props = defineProps(['ewmPic','dataId'])
  const emit = defineEmits(['submit'])
  const formRef = ref<InstanceType<typeof ElForm>>()
  const dialogImageUrl = ref('')
  const dialogVisible = ref(false)
  console.log(props.ewmPic,'===========');
  
  const hideUpload = computed(()=>{
    return !!props.ewmPic
  })
  const beforeUpdata = (file: any) => {
    const is2M = file.size / 1024 / 1024 <= 2
    if (!is2M) {
      ElMessage.warning(`上传的图片}最大支持2M`)
      Remove(file,[])
    }
    return is2M
  }

  const Remove = (file: UploadFile, list: UploadFile[]) => {
    console.log(file,list,'============自动删=');
    props.ewmPic = ''
    emit('submit', props.ewmPic)
  }
  // 上传文件
  const uploadImg = async (file: any) => {
    file = file.raw
    let flag = beforeUpdata(file)
    if (!flag) return;
    return await uploadFile2({
      file,
      fileName: file.name
    })
  }
  // 长传改变
  const handleChange = async (file: UploadFile, list: UploadFile[]) => {
    let existFile = list.slice(0, list.length - 1).find((f) => f.name === file.name)
    if (existFile) {
      ElMessage.error('当前文件已经存在!')
      list.pop()
      return
    }
    const data: any = await uploadImg(file)
    data.id = props.dataId
    props.ewmPic = data.url
    emit('submit', data)
  }
  const handlePictureCardPreview = (file: UploadFile) => {
    dialogImageUrl.value = file.url!
    dialogVisible.value = true
  }
</script>
<style lang="scss" scoped>
  .pre_img_box {
    overflow: hidden;
    .pre_image {
      display: block;
      margin: auto;
      max-height: 400px;
    }
  }
</style>
<style lang="scss">
  .hide .el-upload--picture-card {
    display: none;
  }
  
  .upload_ewm{
    width: 60px;
    height: 60px;
    .el-upload--picture-card{
      width: 100%;
      height: 100%;
    }
    .el-upload-list__item{
      width: 60px;
      height: 60px;
    }
    .upload_icon {
      font-size: 14px;
      line-height: 60px;
      width: 60px;
      height: 60px;
      margin-top: 0;
      text-align: center;
    }
    .ewm_img{
      width:  60px;
      height:  60px;
    }
  }
</style>
